import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/common/res/dimens.dart';
import 'package:oramemo/common/res/gaps.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/common/styles/text_styles.dart';
import 'package:oramemo/common/utils/change_notifier_manage.dart';
import 'package:oramemo/common/utils/keyboard_util.dart';
import 'package:oramemo/core/controllers/auth_controller.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/sendcode_entity.dart';
import 'package:oramemo/pages/login/login/login_area_view.dart';
import 'package:oramemo/pages/login/widgets/my_text_field.dart';
import 'package:oramemo/widget/my_app_bar.dart';
import 'package:oramemo/widget/my_button.dart';
import 'package:oramemo/widget/my_scroll_view.dart';

import '../login/login_logic.dart';
import '../login_router.dart';

/// design/1注册登录/index.html#artboard4
class SMSLoginPage extends StatefulWidget {
  const SMSLoginPage({super.key});

  @override
  _SMSLoginPageState createState() => _SMSLoginPageState();
}

class _SMSLoginPageState extends State<SMSLoginPage>
    with ChangeNotifierMixin<SMSLoginPage> {
  final LoginLogic logic = Get.put(LoginLogic());
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _vCodeController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  TextInputType _currentKeyboardType = TextInputType.emailAddress;

  bool _clickable = false;
  String? _sendUUID;
  static const _phoneAreaChina = '+86';
  String _phoneArea = _phoneAreaChina;
  bool _isPhoneArea = false;

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _phoneController: callbacks,
      _vCodeController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  void _verify() {
    final String name = _phoneController.text;
    final String vCode = _vCodeController.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 4) {
      clickable = false;
    }
    if (vCode.isEmpty || vCode.length < 6) {
      clickable = false;
    }
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  void _login() {
    logic.requestData(
        username: _phoneController.text.toString(),
        uuid: _sendUUID,
        code: _vCodeController.text.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        isBack: false,
        actionName: TextKey.loginTitle.tr,
        onPressed: () {
          Get.toNamed(LoginRouter.loginPage);
        },
      ),
      body: MyScrollView(
        keyboardConfig: KeyboardUtil.getKeyboardActionsConfig(
            context, <FocusNode>[_nodeText1, _nodeText2]),
        padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 20.0),
        children: _buildBody(),
      ),
    );
  }

  List<Widget> _buildBody() {
    return <Widget>[
      Text(
        TextKey.loginSMS.tr,
        style: TextStyles.textBold26,
      ),
      Gaps.vGap16,
      MyTextField(
        focusNode: _nodeText1,
        controller: _phoneController,
        prefixIcon: _isPhoneArea
            ? InkWell(
                onTap: () async {
                  _phoneArea = await Get.to(const PhoneArea());
                  setState(() {});
                },
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(_phoneArea,
                        style: const TextStyle(
                            color: Colours.text_gray, fontSize: 18.0)),
                    const Icon(
                      Icons.arrow_drop_down,
                      color: Colours.text_gray,
                      size: 28.0,
                    ),
                    Gaps.hGap5,
                  ],
                ),
              )
            : null,
        maxLength: 64,
        keyboardType: _currentKeyboardType,
        hintText: _isPhoneArea ? '请输入手机号码' : '请输入邮箱',
      ),
      Gaps.vGap8,
      MyTextField(
        focusNode: _nodeText2,
        controller: _vCodeController,
        maxLength: 6,
        keyboardType: TextInputType.number,
        hintText: TextKey.inputVerifyCode.tr,
        getVCode: () async {
          SendcodeEntity? response;
          if (_isPhoneArea) {
            if (_phoneArea == _phoneAreaChina) {
              response = await DefaultApi()
                  .sendSmsChinaGet(phone: _phoneController.text.toString());
            } else {
              response = await DefaultApi().sendSmsInternationalGet(
                  phone: _phoneController.text.toString());
            }
          } else {
            response = await AuthController.to
                .sendEmail(_phoneController.text.toString());
          }
          _sendUUID = response?.uuid;
          return Future<bool>.value(true);
        },
      ),
      Gaps.vGap5,
      Container(
        alignment: Alignment.centerLeft,
        child: InkWell(
          onTap: () async {
            setState(() {
              _isPhoneArea = !_isPhoneArea;
              _currentKeyboardType = _isPhoneArea
                  ? TextInputType.phone
                  : TextInputType.emailAddress;
              _phoneController.text = '';
              _nodeText1.unfocus();
            });
            await Future.delayed(const Duration(milliseconds: 100));
            _nodeText1.requestFocus();
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                RichText(
                  text: TextSpan(
                    text: _isPhoneArea ? '切换为邮箱验证码' : '切换为手机验证码',
                    style: Theme.of(context)
                        .textTheme
                        .titleSmall
                        ?.copyWith(fontSize: Dimens.font_sp14),
                  ),
                ),
                // Icon(Icons.keyboard_arrow_down,color: Colours.text_gray, size: 24.0),
              ],
            ),
          ),
        ),
      ),
      Gaps.vGap24,
      MyButton(
        onPressed: _clickable ? _login : null,
        radius: 8,
        text: TextKey.loginButton.tr,
      ),
    ];
  }
}
